<template>
	<view :style="{height:listViewHeight + 'px'}">
		<scroll-view class="scroll" scroll-y="true" :scroll-top="scrollTop" scroll-with-animation="true"
			@scroll="scroll" @scrolltolower="scrollToLower" refresher-enabled="true" :refresher-threshold="50"
			:refresher-triggered="triggered" @refresherrefresh="refresherRefresh">
			<slot name="head"></slot>
			<template>
				<view v-for="(article,index) in articleList" :key="article.id">
					<article-item :article="article" :index="index" @itemClick="articleItemClick"
						@likeClick="articleLikeClick" />
				</view>
			</template>
			<slot name="footer"></slot>
		</scroll-view>

		<custom-back-top :scroll-top="backTopDistance" top="600" @backToTop="backToTop"></custom-back-top>
	</view>
</template>

<script>
	export default {
		name: "article-list",
		props: {
			listViewHeight: {
				type: Number,
				required: true,
				default: 0,
			},
			articleList: {
				type: Array,
				required: true,
			}
		},
		data() {
			return {
				windowHeight: 0,
				backTopDistance: 0,
				// 处理回到顶部的问题
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				// 处理下拉刷新
				triggered: false,
				_freshing: false,
			};
		},
		onLoad() {
			this._freshing = false;
			setTimeout(() => {
				//触发onRefresh来加载自己的数据，如果不用这种方式，不要在此改变triggered的值 
				this.triggered = true;
			}, 1000);
		},
		methods: {
			// 点击新闻条目触发
			articleItemClick(index, article) {
				this.$emit("itemClick", index, article);
			},
			// 点击喜欢按钮触发
			articleLikeClick(index, isCollect) {
				this.$emit("likeClick", index, isCollect);
			},
			// scroll滚动时触发
			scroll(event) {
				this.backTopDistance = event.detail.scrollTop;
				this.old.scrollTop = event.detail.scrollTop
			},
			// scroll滑动到底部触发
			scrollToLower() {
				this.$emit("loadMoreData");
			},
			refresherRefresh(event) {
				if (this._freshing) return;
				this._freshing = true;
				if (!this.triggered) //界面下拉触发，triggered可能不是true，要设为true  
					this.triggered = true;
				setTimeout(() => {
					this.triggered = false; //触发onRestore，并关闭刷新图标  
					this._freshing = false;
				}, 3000)
			},
			// 点击回到顶部按钮触发
			backToTop() {
				this.scrollTop = this.old.scrollTop;
				this.$nextTick(() => {
					this.scrollTop = 0
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.scroll {
		width: 100%;
		height: 100%;
	}
</style>
